package org.Lin.client;


import javax.swing.*;
import java.awt.*;

import org.Lin.util.AESUtil;
import org.Lin.util.HashUtil;
import org.json.JSONObject;

public class RegisterClient {
    private JFrame frame;
    private JTextField userIDField, nameField, emailField;
    private JPasswordField passwordField;

    public void show() {
        frame = new JFrame("用户注册");
        frame.setSize(400, 350);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLayout(new GridLayout(6, 2));

        frame.add(new JLabel("用户ID:"));
        userIDField = new JTextField();
        frame.add(userIDField);

        frame.add(new JLabel("用户名:"));
        nameField = new JTextField();
        frame.add(nameField);

        frame.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        frame.add(passwordField);

        frame.add(new JLabel("邮箱:"));
        emailField = new JTextField();
        frame.add(emailField);

        JButton registerButton = new JButton("注册");
        JButton backButton = new JButton("返回登录");

        registerButton.addActionListener(e -> {
            String userID = userIDField.getText();
            String name = nameField.getText();
            String password = new String(passwordField.getPassword());
            String email = emailField.getText();

            JSONObject request = new JSONObject();
            request.put("type", "register");
            request.put("userID", userID);
            request.put("name", name);
            request.put("password", HashUtil.hashPassword(password));
            request.put("email", email);

            try {
                String encrypted = AESUtil.encrypt(request.toString());
                NetworkClient.send(encrypted);
                JOptionPane.showMessageDialog(frame, "注册请求已发送");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(frame, "发送失败: " + ex.getMessage());
            }
        });

        backButton.addActionListener(e -> {
            new LoginClient().show();
            frame.dispose();
        });

        frame.add(registerButton);
        frame.add(backButton);
        frame.setVisible(true);
    }
}

